


console.log("get ozon seller load");


function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    };
    return 0;
 }


startNextSeller();

function getFirstPageByAjax(dataobj,try_time){
    console.log(dataobj);
    console.log("try_time:"+try_time);
    if(!dataobj.data.url){
        console.log("no url!! no data!!")
        return;
    }
    var url = dataobj.data.url
    console.log("getFirstPageByAjax_:"+url)
    var id = dataobj.data.id;
    $.ajax({
      url: url,
      method: 'GET',
      dataType: 'html',
      success: function(htmlContent) {
        // 将 HTML 页面内容解析为 DOM 元素
        const dom = $($.parseHTML(htmlContent));
        var body = "";
        var tf_state = "";
        var noresult =false;
        //console.log(htmlContent);
        updateFirstPageByDom(dom,dataobj);
      },
      error: function(xhr, status, error) {
        console.log('Ajax error: ', error);
        if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
            //中断
        }else{
            setTimeout(() => {
                    getFirstPageByAjax(dataobj,try_time+1)
            },try_time * 20000);
        }

      }
    });
}



function updateFirstPageByDom(dom,dataobj){
    var noresult = false;
    var tf_state = "";
    var body = "";
    dom.find("div").each(function(e){
        var indexid=$(this).attr("id")+"";
        if (indexid.indexOf("searchResultsV2-") != -1 ){
            console.log($(this).attr("id"));
            body = $(this).attr("data-state");
        }
        if (indexid.indexOf("state-megaPaginator") != -1 ){
             var megaPaginatorData = $(this).attr("data-state");
             console.log(megaPaginatorData);
             const regex = /tf_state=(.*?)[\"'<>` &;]/;
             const match = megaPaginatorData.match(regex);
             console.log(match);
             if(match && match[1]){
                tf_state = match[1];
             }
        }
        if(indexid.indexOf("state-searchResultsError-") != -1){
            noresult = true;
        }
    });
    console.log("tf_state_"+tf_state);
    console.log("noresult:"+noresult);
    var itemCount = 0;
    if(noresult==true){
        itemCount=0;
    }else if(body){
        var bodyObj = JSON.parse(body);
        var itemCount = bodyObj.items.length;
    }else{
        //没有结果并且noresult也没有拿到，应该是被拦截了
        console.log("没有结果并且noresult也没有拿到，应该是被拦截了");
        return;
    }
    //console.log(body);
    console.log(itemCount);
    var page = 1 ;
    var type="ozonfirstpage";
    var is_finish = 0;
    if(itemCount < 12){
        is_finish = 1;
    }
    console.log("first_page_is_finish:"+is_finish);
    $.post("https://www.gongrenbao.cn/index.php?c=api/ozon/upozonseller&type=firstpage",
          {data:body,id:dataobj.data.id,is_finish:is_finish},
          function(data){
                console.log("items_size_page_1:"+itemCount)
                if(itemCount < 12 || noresult==true){
                    startNextSeller();
                }else{
                    checkFormLoad(2,tf_state,dataobj);
                }
          },
      "text");

}



function checkFormLoad(page,tf_state,dataobj) {
  console.log('ajax  page='+page)
  const urlparam = new URL(dataobj.data.url);
  const pathAndParams = urlparam.pathname + urlparam.search;
  var urlParam= encodeURIComponent(pathAndParams+"&tf_state="+tf_state+"&layout_container=megapaginator&layout_page_index="+page+"&page="+page);
  console.log(urlParam);
  var url ="https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url="+urlParam;

  setTimeout(() => {
    $.ajax({
      url: url,
      success: (function(page){
        return function(data){
            var widgetStates = JSON.stringify(data.widgetStates);
            if(!widgetStates || widgetStates.length < 200 ){//停止更新
                $.post("https://www.gongrenbao.cn/index.php?c=api/ozon/upozonseller",
                   {data:body,id:dataobj.data.id,is_finish:1},
                        function(data){
                    },
               "text");
               startNextSeller();
            }else{
                var body = JSON.stringify(data);
                var type="ozonlist";
                var is_finish = 0;
                for (let key in data.widgetStates) {
                    var obj = JSON.parse(data.widgetStates[key]);
                    console.log("items_size_page_"+page+":"+obj.items.length)
                    if(obj.items.length<12){
                        is_finish = 1;
                        break;
                    }
                }
                if(page>=3){
                    console.log("max page finish:"+page)
                    is_finish = 1;
                }
                console.log("page_"+page+"_is_finish:"+is_finish);
                $.post("https://www.gongrenbao.cn/index.php?c=api/ozon/upozonseller",
                  {data:body,id:dataobj.data.id,is_finish:is_finish},
                  function(data){
                     if(is_finish==1){
                        startNextSeller();
                    }else{
                        checkFormLoad(page+1,tf_state,dataobj);
                    }
                  },
              "text");
            }
        }
      })(page),
      error: function(){
         console.log('ajax error page='+page)
         if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
        }else{
             checkFormLoad(page,tf_state,dataobj);
        }
      }
    });

  }, 5000);
}

function startNextSeller(){
    var type="getozonseller";
    chrome.runtime.sendMessage({ data: {type}, close: false });
}

chrome.runtime.onMessage.addListener(async (msg, sender) => {
  console.log(msg)
  setTimeout(() => {
     //var msgObj = JSON.parse(msg);
     getFirstPageByAjax(msg,1);
  }, 5000);

})







